/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jreque.persistance;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Properties;

/**
 * Fatory for persistance layer classes
 * @author rzezioo
 */
public class QueuePersistanceFactory {
    /**
     * Creates an instance of a persistance layer class using the supplied properties.
     * The class of the returned object is specified by the persistance_class property
     * Any other properties are class-dependent.
     * @param p - Properties describing the desired persistance layer object
     * @return `The persistance layer object
     * @throws ClassNotFoundException if the class specified in the persistance_class
     * property cannot be found
     * @throws IllegalArgumentException if the specified class doesn't implement the
     * IQueuePersistance interface.
     */
    public static IQueuePersistance getInstanceForProperties(Properties p) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException {
        String className = p.getProperty("persistance_class");
        Class clazz = Class.forName(className);
        if(!IQueuePersistance.class.isAssignableFrom(clazz)){
            throw new IllegalArgumentException("The specified class isn't a persistance layer class.");
        }
        try{
            Constructor c = clazz.getConstructor(Properties.class);
            Object obj = c.newInstance(p);
            if(obj instanceof IQueuePersistance) {
                return (IQueuePersistance)obj;
            }
        } catch (NoSuchMethodException e) {}
        try{
            Constructor c = clazz.getConstructor();
            Object obj = c.newInstance();
            if(obj instanceof IQueuePersistance) {
                return (IQueuePersistance)obj;
            }
        } catch (NoSuchMethodException e) {}
        throw new InstantiationException("Brak odpowiedniego konstruktora dla klasy " + className);
    }
}
